package de.gameduell.framework.gui.behavior {
	import de.gameduell.framework.gui.wrapper.SpriteWrapper;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;	

	/**
	 * @author cbra
	 */
	public class DragBehavior extends EventDispatcher implements IBehavior{
			
//		public static const START_DRAG:String = "startdrag";
//		public static const STOP_DRAG:String  = "stopdrag";
		
		private var _sprite:SpriteWrapper;
		private var _active:Boolean;
		private var isDragging:Boolean;
		
		public function DragBehavior() {
			_active = true;
			_sprite = new SpriteWrapper(new Sprite());
		}
		
		public function init(aSprite:SpriteWrapper):void{
			_sprite = aSprite;
			var dragger:Sprite = _sprite.getChildByName("dragger") as Sprite;
			var eventDispatcher:EventDispatcher = dragger == null ? _sprite.sprite : dragger;
		
			eventDispatcher.addEventListener(MouseEvent.MOUSE_DOWN, startDrag);
			eventDispatcher.addEventListener(MouseEvent.MOUSE_UP, stopDrag);
			eventDispatcher.addEventListener(Event.REMOVED, removed);
		}
		
		private function removed(event:Event):void{
			if(event.target == _sprite){
				stopDrag();
			}
		}
		
		private function startDrag(event:Event):void{
			if(!isDragging){
				_sprite.startDrag();
				isDragging = true;
				dispatchEvent(new BehaviorEvent(BehaviorEvent.START_DRAG,_sprite.name));
			}
		}

		public function stopDrag(event:Event = null):void {	
			if(isDragging){
				_sprite.stopDrag();
				isDragging = false;
				dispatchEvent(new BehaviorEvent(BehaviorEvent.STOP_DRAG, _sprite.name));
			}
		}

		public function set active(isActive:Boolean):void {
			_active = isActive;
			if(isActive){
				_sprite.addEventListener(MouseEvent.MOUSE_DOWN, startDrag);
				_sprite.addEventListener(MouseEvent.MOUSE_UP, stopDrag);
			}else{
				_sprite.removeEventListener(MouseEvent.MOUSE_DOWN, startDrag);
				_sprite.removeEventListener(MouseEvent.MOUSE_UP, stopDrag);
			}
		}
		
		public function get active():Boolean{
			return _active;
		}
		
		public function getEventTypes():Array {
			return new Array(BehaviorEvent.START_DRAG,BehaviorEvent.STOP_DRAG);
		}
	}
}
